// 提问仓库
import io from "socket.io-client";
const socket = io("http://localhost:3200"); // 替换为您的服务器地址

import {
  getDefaultRoomAPI,
  getMessageAPI,
  getMyCreateRoomsAPI,
  getMyRoomsAPI,
} from "@/api/socket";
import { findUserInfoAPI } from "@/api/index";
const state = {
  myInfo: {
    img: "",
    name: "",
  },
  currentRoomInfo: {},
  defaultRoom: [],
  myRoomList: [],
  // 我加入的房间 --- type = 0
  myJoinRoom: [],
  messageList: [],
  showCurrentUserInfo: {},
};

const actions = {
  async getDefaultRoom({ commit }) {
    const res = await getDefaultRoomAPI();
    if (res.status == 0) {
      commit("GETDEFAULTROOM", res.data);
    }
  },
  async getMyRoomList({ commit }) {
    const res = await getMyCreateRoomsAPI();
    if (res.status == 0) {
      commit("GETMYROOMLIST", res.data);
    }
  },
  initCurrentRoomInfo({ commit }, data) {
    commit("INITCURRENTROOMINFO", data);
  },
  // { room_id: room_id, page: page, pageSize: pageSize }
  async getMessageList({ commit }, { room_id, page, pageSize }) {
    const res = await getMessageAPI(room_id, page, pageSize);
    if (res.status == 0) {
      commit("GETMESSAGELIST", res.data);
    }
  },
  async showCurrentUserInfo({ commit }, user_id) {
    const res = await findUserInfoAPI(user_id);
    if (res.status == 0) {
      commit("SHOWCURRENTUSERINFO", res.data);
    }
  },
  async updateMessageList({ commit }, { room_id, page, pageSize }) {
    const res = await getMessageAPI(room_id, page, pageSize);
    if (res.status == 0) {
      commit("UPDATEMESSAGELIST", res.data);
    }
  },
  async getMyJoinRoom({ commit }, type) {
    const res = await getMyRoomsAPI(type);
    if (res.status == 0) {
      console.log("我加入的群聊", res.data);
      commit("GETMYJOINROOM", res.data);
    }
  },
  // 点击分页添加
};

const mutations = {
  GETMYROOMLIST(state, data) {
    state.myRoomList = data;
  },
  GETDEFAULTROOM(state, data) {
    state.defaultRoom = data;
  },
  INITCURRENTROOMINFO(state, data) {
    state.currentRoomInfo = data;
  },
  GETMESSAGELIST(state, data) {
    state.messageList = data;
    // 按照时间属性对整个数组进行排序
    state.messageList.sort((a, b) => a.id - b.id);
  },
  SHOWCURRENTUSERINFO(state, data) {
    state.showCurrentUserInfo = data;
  },
  GETMYJOINROOM(state, data) {
    state.myJoinRoom = data;
  },
  updateMessageList(state, msg) {
    state.messageList.push(msg);
  },
  UPDATEMESSAGELIST(state, data) {
    state.messageList.unshift(...data);
    // 按照时间属性对整个数组进行排序
    state.messageList.sort((a, b) => a.id - b.id);
  },
};

const getters = {};

export default {
  state,
  mutations,
  actions,
  getters,
};
